package com.grademaster.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.MajorPageDto;
import com.grademaster.entity.Majors;
import com.grademaster.mapper.MajorsMapper;
import com.grademaster.service.MajorsService;
import com.grademaster.util.LoginUtil;
import com.grademaster.vo.MajorVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
* @author Administrator
* @description 针对表【majors(专业表)】的数据库操作Service实现
* @createDate 2024-06-25 13:57:06
*/
@Service
public class MajorsServiceImpl extends ServiceImpl<MajorsMapper, Majors>
    implements MajorsService {

    @Autowired
    private MajorsMapper majorsMapper;

    /**
     * 根据分页信息获取所有专业信息
     *
     * @param majorPageDto
     * @return
     */
    @Override
    public R getAllMajorsByPage(MajorPageDto majorPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        List<MajorVO> majorVOList = majorsMapper.findMajorsWithPagination(majorPageDto.getPage(), majorPageDto.getPageSize(), majorPageDto.getMajorName());
        Integer count = majorsMapper.countMajors(majorPageDto.getMajorName());
        Page<MajorVO> page = new Page<>(majorPageDto.getPage(), majorPageDto.getPageSize(),count);
        page.setRecords(majorVOList);
        return R.success(page);
    }
    /**
     * 导出专业信息到Excel
     *
     * @param majorPageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(MajorPageDto majorPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return ResponseEntity.badRequest().build();
        }
        List<MajorVO> majorVOList = majorsMapper.findMajorsWithPagination(1, 2000, majorPageDto.getMajorName());
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Majors"
        Sheet sheet = workbook.createSheet("Majors");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"专业ID", "学院名称", "专业名称"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (MajorVO major : majorVOList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(major.getMajorId());
            row.createCell(1).setCellValue(major.getCollegeName());
            row.createCell(2).setCellValue(major.getMajorName());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=majors.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 获取所有专业信息
     *
     * @return
     */
    @Override
    public R getAllMajors() {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        return R.success(this.list());
    }

    /**
     * 新增或修改专业信息
     *
     * @return
     */
    @Override
    public R addOrEditMajor(Majors majors) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        if (majors.getMajorId() != null){
            return R.success(this.updateById(majors));
        }
        //添加专业
        return R.success(this.save(majors));
    }

    /**
     * 删除专业信息
     *
     * @param majorId
     * @return
     */
    @Override
    public R deleteMajor(String majorId) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        String[] ids = majorId.split(",");
        for (String id : ids) {
            this.removeById(id);
        }
        return R.success("删除成功");
    }


}




